The current best practice for using git to manage collaborative software projects is known as trunk-based development. Under this model, small changes are frequently made in different branches, then merged into the main “trunk” (i.e. the main or master branch) of the repo after passing peer review. The steps look like this:
An issue is opened
a developer or user notices a bug, requests a feature, or asks a question.
Engage in the issue comments
to clarify the issue, ask for a reproducible example, etc.
Work on the issue
create a new branch and switch to it.
write tests that will pass when the issue is resolved.
write or edit code to resolve the issue.
(possibly) write more tests to make sure edge cases and failure modes are handled.
write/update documentation if needed.
make sure your tests pass and the package still builds.
Create a pull request
assign or request a reviewer.
the reviewer reviews your code.
you make any requested changes.
the reviewer approves your pull request once they’re happy with it.
merge the pull request.
Celebrate that you resolved an issue!
You can have multiple issues open at any stage of the process at a time. You might start working on a feature, switch to fixing a time-sensitive bug and resolve it, then later go back to working on that feature. Meanwhile, collaborators are working on other issues too! This process enables highly collaborative and asynchronous work.
Continuous integration: what & why?
git + ci = magic ✨
It would be a bummer if you or a collaborator forgot a crucial step of the process, like running the unit tests or linting your code, and accidentally merged buggy/broken/bad code into the main branch of your project. The good news is: You don’t have to remember everything! Let the machines do it for you automatically!
Continuous integration is a practice where tests and other code quality checks are automatically run before code changes are merged into the main branch.
How does this modify our git workflow? When we open a pull request or push a commit to main, the CI service will run a workflow we define to run our checks, so we don’t have to do it manually!
CI service options
GitHub Actions
Travis
Jenkins
CircleCI
Azure DevOps
We’ll use GitHub Actions because it’s easy to setup when you already have your repo hosted on GitHub, and they provide a lot of computing resources for free.
Building a CI workflow with GitHub Actions
We’re going to create a CI workflow that runs on all pushes and pull requests to the default branch (typically “main” or “master”). Workflows are defined with YAML files to specify how to configure the machine that runs the workflow, install dependencies, and run commands.
Let’s start by creating a small workflow that prints “Hello, world!” and lists the files in the package.
Before we can get started using GitHub Actions, we’ll need to make sure we configure our repo settings to allow Actions to run and push changes.
Enable Actions
On Github.com, go to your repository, click Settings and under ‘Code and automation’ click Actions -> General. Under ‘Actions permissions’, select Allow all actions and reusable workflows and click Save.
Allow Actions to read & write
Next, scroll down to the bottom of the page. Under ‘Workflow permissions’, select Read and write permissions and click Save.
Now we’re ready to start using GitHub Actions for our projects!
Getting started
Every GitHub Actions workflow resides in .github/workflows/ and needs:
on – events that trigger the workflow
jobs – list of independent jobs each with steps to run in sequence.
steps – each step specifies a third party action to uses with uses, or specifies shell code to run.
Workflow 1: .github/workflows/greet.yml
# name of the workflowname: greet# when the workflow should runon:push:branches:- main- masterpull_request:branches:- main- master# independent jobs in the workflowjobs: # this workflow just has one job called "greet"greet: # the operating system to use for this workflowruns-on: ubuntu-latest # list of steps in the workflowsteps: # use an action provided by github to checkout the repo-uses: actions/checkout@v3 # a custom step that runs a couple shell commands-name: List run: | echo "listing files in the bioinitio directory" ls bionitio # a custom step that runs R code-name: Greetrun: print("Hello, world!") # Replace `shell: Rscript {0}` with `shell: python {0}` to run Python code instead!shell: Rscript {0}
Create the “Hello world” action
Open an issue with the title “Set up continuous integration”.
Switch to a new branch called ci.
Add the workflow (Workflow 1) to your repo at .github/workflows/greet.yml.
Replace bionitio with the name of your package.
Commit and push it to GitHub.
Finally, open a pull request from your new branch into main.
Did your workflow run? On GitHub, go to the Actions tab of your repo. Opening the pull request should have triggered the workflow to run.
Once the workflow finishes (about 15 seconds), it will either have a green checkmark (✅) for success or a red X (❌) for failure.
Click on the workflow run. Then under ‘jobs’, click on the job ‘greet’. You’re now viewing the log file for the job. You can click on the arrows to expand the details for each step.
You can also see the status of the action from the Pull Request summary page. Keep your pull request open. We’re going to continue pushing commits to the ci branch as we add new steps to the workflow.
greet status
In Slack, react with ✅ or ❌ to indicate the status of your workflow.
Test suite
This initial “hello world” workflow is cute, but not very useful. Let’s edit the workflow to run our test suite for us automatically!
The r-lib actions assume that the top level of your repo is the same as the top level of your R package. If that’s not the case, you’ll need to specify the working-directory.
For my example project, bionitio-r is the top level of the git repo, and from there the R package resides in bionitio:
name: CIon:push:branches:- main- masterpull_request:branches:- main- masterjobs:build:runs-on: ubuntu-lateststeps:-uses: actions/checkout@v3-name: Set up Python 3.11uses: actions/setup-python@v3with:python-version:"3.11"-name: Install dependencies run: | python -m pip install --upgrade pip pip install pytest if [ -f requirements.txt ]; then pip install -r requirements.txt fi-name: Test with pytest run: | pytest .
In each of these workflows, the action checks out the repo, installs R or Python, installs the dependencies of the package, then runs the tests. If any of your tests fail, the whole actions workflow will fail too.
Testing with CI
In your ci branch, modify your CI workflow to run the test suite, then commit and push your changes. Does the CI workflow succeed or fail?
You may get failures if you haven’t been running your unit tests as you develop your code base. Take a few minutes to open issues for each test that failed.
React to the slack message with ✅ when you’re finished opening issues or now if the workflow completed successfully.
Workflow status badges
Each Actions workflow has a status badge that indicates whether the action is passing or failing. You may have come across status badges in GitHub README files of packages you use. Putting a CI status badge in the README file is a popular way for project maintainers to prominently display that CI is set up and it’s working!
Add the workflow status badge to your README
Under the Actions tab, click the name of the workflow (e.g. ci), click the triple dots menu (...) in the upper right corner, and select Create status badge.
In the pop-up menu, click Copy status badge Markdown, paste it into your README.md file, then commit and push your change on the ci branch.
React to the slack message with ✅ when you’re finished.
Now anyone who takes a look at your README file will see that your project uses continuous integration!
Lint and style code
Many large software projects follow a specific coding style guide to make sure their code base is consistent and easy to read.
Good coding style is like correct punctuation: you can manage without it, butitsuremakesthingseasiertoread.
A linter checks your code to make sure you conform to a style guide and raises warnings if your code doesn’t conform. A code formatter or styler modifies your code to make it conform to a style guide. There is a lot of overlap in the problems that linters and formatters can catch, but linters additionally warn about not only style problems but more serious problems like syntax errors.
When adding these tools to CI, make sure you run the formatter before the linter, so the linter will only complain about problems that the formatter can’t fix. Since the code formatter modifies our code, we will also need to commit and push the code changes using the GitHub Actions bot as the author.
style R .github/workflows/ci.yml
name: CIon:push:branches:- main- masterpull_request:branches:- main- masterenv: # configure environment variables for git commitsactor:"41898282+github-actions[bot]"jobs:build:runs-on: ubuntu-latestenv:GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }}R_KEEP_PKG_SOURCE:yessteps:-uses: actions/checkout@v3-uses: r-lib/actions/setup-r@v2with:use-public-rspm:true-uses: r-lib/actions/setup-r-dependencies@v2with: # also install styler & lintrextra-packages: any::rcmdcheck, any::styler, any::lintrneeds: checkworking-directory: bionitio-name: Configure git # use the environment variable we set above run: | git config --local user.email "${actor}@users.noreply.github.com" git config --local user.name "$actor"-name: Checkuses: r-lib/actions/check-r-package@v2with:args:'c("--no-manual", "--as-cran")'working-directory: bionitio-name: Style & lint run: | styler::style_dir(".") lintr::lint_dir(".")shell: Rscript {0}-name: Commit and push changes run: | git add . git commit -m "🎨 Style code" || echo "No changes to commit" git push
Note
The check-r-package action creates files in /package/check/. We don’t want git to track them, so we need to add the check dir to the gitignore file:
R .gitignore
.Rproj.user.Rhistory.RData.Ruserdatacheck/
style Py .github/workflows/ci.yml
name: CIon:push:branches:- main- masterpull_request:branches:- main- masterenv: # configure environment variables for git commitsactor:"41898282+github-actions[bot]"jobs:build:runs-on: ubuntu-lateststeps:-uses: actions/checkout@v3-name: Set up Python 3.11uses: actions/setup-python@v3with:python-version:"3.11"-name: Install dependencies run: | python -m pip install --upgrade pip pip install pytest black flake8 # also install black & flake8 if [ -f requirements.txt ]; then pip install -r requirements.txt fi-name: Configure git # use the environment variable we set above run: | git config --local user.email "${actor}@users.noreply.github.com" git config --local user.name "$actor"-name: Test run: | pytest .-name: Format & lint run: | black . # first run black, then run flake8 flake8 --extend-ignore E203 --max-line-length 88 .-name: Commit and push changes run: | git add . git commit -m "🎨 Style code" || echo "No changes to commit" git push
Note
flake8 is not 100% compatible with black by default. Here we direct flake8 to ignore one of its errors (--extend-ignore E203) and increase the maximum allowed line length (--max-line-length 88) to make flake8 compatible with black.
There are several key changes we made to this workflow to make sure our styling and linting would work:
Set a global environment variable called actor with the username of the GitHub Actions bot.
Configure the git username and email to point to the GitHub Actions bot, using the environment variable we created in above.
Install additional dependencies for linting and formatting the code.
Run the code formatter and linter.
Commit any changes and push to origin.
Style & lint your code
You know the drill! Modify your workflow to style and lint your code, and see what happens when you push it to GitHub.
Does the linter raise any errors? If so, take a moment to open issues for the errors you need to fix. React to the slack message with ✅ when you’re finished opening issues or now if you’re code is already lint-free.
Are your tests failing?
If you have some failing tests, the workflow will fail before it gets to the lint & style step. You can temporarily comment-out the test step with hashes (#) so you can continue through this tutorial, but don’t forget to uncomment these lines later!
Code coverage
Code coverage is the percentage of your source code that is covered by unit tests. Generally the higher the code coverage, the better. However, a code coverage of 100% doesn’t guarantee that your package doesn’t have any bugs, it only means that every line of code is run at least once by your test suite. It can be a useful metric to see where there are holes in your tests.
Codecov.io is a free tool for open source projects that pairs nicely with GitHub Actions for generating code coverage reports! Let’s set it up now.
login to codecov
Go to https://about.codecov.io/ and Login with GitHub. If this is the first time you’re connecting Codecov and GitHub, you may need to grant Codecov permission to read your repositories.
Once you’re logged in, you should see a list of all your GitHub repos (and maybe also those of any organizations you’re a member of). Scroll down to your repo for this class and click setup repo.
Follow the instructions on the next page to set up code coverage for your repo. Just do Step 1 and Step 2 now; we need to make some custom modifications to Step 3 for our projects.
Warning
Your CODECOV_TOKEN should be kept secret. Don’t paste it anywhere except for in your repository’s Actions secrets.
Codecov setup
React to the message on Slack with 1️⃣ for Step 1 and 2️⃣ for Step 2 once you complete them. Don’t do the other Steps yet.
Edit the workflow
We’ll need to make sure the test suite generates a report that codecov can ingest.
For Python, you’ll need to install an additonal plugin called pytest-cov and set the --cov flag when you run pytest. You can paste the codecov step anywhere after the test step of your workflow.
Running pytest with --cov generates an xml file. You don’t want to track that with git, so add coverage.xml to your gitignore file:
Py .gitignore
__pycache__/coverage.xml
codecov Py .github/workflows/ci.yml
name: CIon:push:branches:- main- masterpull_request:branches:- main- masterenv:actor:"41898282+github-actions[bot]"jobs:build:runs-on: ubuntu-lateststeps:-uses: actions/checkout@v3-name: Set up Python 3.11uses: actions/setup-python@v3with:python-version:"3.11"-name: Install dependencies run: | python -m pip install --upgrade pip pip install pytest pytest-cov black flake8 # add pytest-cov plugin if [ -f requirements.txt ]; then pip install -r requirements.txt fi-name: Configure git run: | git config --local user.email "${actor}@users.noreply.github.com" git config --local user.name "$actor"-name: Test run: | pytest --cov=bionitio tests/ # specify your package & test paths-name: Upload coverage reports to Codecovuses: codecov/codecov-action@v3-name: Format & lint run: | black . flake8 --extend-ignore E203 --max-line-length 88 .-name: Commit and push changes run: | git add . git commit -m "🎨 Style code" || echo "No changes to commit" git push
For R, the covr package runs the test suite, generates a report, and uploads it to codecov all with one function. You don’t need codecov’s Action as in the Python workflow, because covr handles that for you.
Once your modified CI workflow has completed successfully with the new codecov step, you’ll be able to view coverage reports for your repo on codecov.io and see them in your pull requests. However, if your tests aren’t passing, codecov won’t be able to generate a report.
codecov setup
React to the Slack message with: - ✅ once your CI workflow completes successfully with codecov and you can see the coverage report. - 🔨 if you need to fix your tests before the workflow can complete.
codecov status badge
Codecov has a nifty status badge that we can display in our README file too.
Copy and paste the following into your README.md, then replace GITHUB_USERNAME and GITHUB_REPO in both the image and link URLs.
The color of the badge changes from red to green as coverage increases. If your tests aren’t passing or the codecov upload action didn’t work, it will display unknown as the coverage for now.
codecov badge
React to the Slack message with ✅ once you’ve added the codecov badge to your README.
Interpreting code coverage
Generally, higher code coverage is better. However, 100% code coverage doesn’t guarantee that your code is free of bugs, and not all code strictly needs to be tested. Focus on writing unit tests that test your assumptions about how your code works and test the most important components of your project.
Document
R: roxygen2
Python: sphinx
Setup a documentation website
GitHub Pages will host your docs for free!
Resources
Related topics & resources to explore
Other ways to trigger workflows
On release
Manual dispatch
Cron schedule
Branch protection
Prevent PRs from getting merged until checks pass.
Pre-commit hooks
Run checks, style code, etc before you even commit
More actions created by Posit: https://github.com/r-lib/actions